﻿package Interface.ShopClasses
{
	import Interface.ArrowButton;
	
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.display.MovieClip;

	public class ShopScroller extends Sprite
	{
		private const CPaginationY:int = 243;
		
		private var FContainer:ShopContainer;
		private var FLeft:ArrowButton;
		private var FRight:ArrowButton;
		private var FPagination:MovieClip;
		private var FCurrentPageLabel:PageLabel;
		
		public function ShopScroller():void
		{
			FContainer = getChildByName('Container') as ShopContainer; 
			FLeft = getChildByName('Left') as ArrowButton; 
			FRight = getChildByName('Right') as ArrowButton;		
			
			FLeft.addEventListener(MouseEvent.MOUSE_DOWN, OnLeft);
			FRight.addEventListener(MouseEvent.MOUSE_DOWN, OnRight);
			FLeft.enabled = false;
			FRight.enabled = false;
		}
		
		public function Add(AItem:ShopItem):void
		{
			FContainer.Add(AItem);			
		}		
		
		public function SetupPages():void
		{
			FPagination = new MovieClip();			
			var vPageLabel:PageLabel;
			var vLabelsShift:Number = new Number();
			
			for(var i:int = 0; i < FContainer.PagesCount; i++)
			{
				vPageLabel = new PageLabel((i + 1).toString());				
				vPageLabel.x = vLabelsShift;
				vPageLabel.addEventListener(MouseEvent.MOUSE_DOWN, OnPageLabelClick);
				vPageLabel.ID = i;
				vLabelsShift += vPageLabel.width;
				FPagination.addChild(vPageLabel);
			}			
			FPagination.x = (550 - FPagination.width) / 2;
			FPagination.y = CPaginationY;
			addChild(FPagination);			
			
			Reset();
			
			FRight.enabled = FContainer.PagesCount > 0;
		}
		
		private function OnLeft(e:MouseEvent):void
		{
			if (e.target.enabled)
			{				
				FContainer.MoveLeft();
				UpdateArrows();
			}
		}
		
		private function OnRight(e:MouseEvent):void
		{
			if (e.target.enabled)
			{				
				FContainer.MoveRight();
				UpdateArrows();
			}
		}
		
		private function OnPageLabelClick(e:MouseEvent):void
		{
			(e.target.parent as PageLabel).Selected = false;
			FContainer.Page = (e.target.parent as PageLabel).ID;
			UpdateArrows();
		}
		
		private function UpdateArrows():void		
		{
			FLeft.enabled = !FContainer.IsFirstPage;
			FRight.enabled = !FContainer.IsLastPage;
			
			if(FCurrentPageLabel)
				FCurrentPageLabel.Selected = false;				
			try
			{
				FCurrentPageLabel = FPagination.getChildAt(FContainer.Page) as PageLabel;
			}
			catch(e:Error)
			{
				FCurrentPageLabel = null;
			}
			FCurrentPageLabel.Selected = true;
		}
		
		public function Reset():void
		{
			FContainer.Reset();
			UpdateArrows();
		}
	}	
}
